<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('信用大厅')" />
	<th:block th:include="include :: layout-latest-css" />
	<th:block th:include="include :: ztree-css" />
</head>
<body class="gray-bg">
<div class="ui-layout-west">
	<div class="box box-main">
		<div class="box-header">
			<div class="box-title">
				<i class="fa icon-grid"></i>评分
			</div>
			<div class="box-tools pull-right">
				<a type="button" class="btn btn-box-tool" href="#" onclick="dept()" title="管理部门"><i class="fa fa-edit"></i></a>
				<button type="button" class="btn btn-box-tool" id="btnExpand" title="展开" style="display:none;"><i class="fa fa-chevron-up"></i></button>
				<button type="button" class="btn btn-box-tool" id="btnCollapse" title="折叠"><i class="fa fa-chevron-down"></i></button>
				<button type="button" class="btn btn-box-tool" id="btnRefresh" title="刷新评分"><i class="fa fa-refresh"></i></button>
			</div>
		</div>
		<div class="ui-layout-content">
			<div id="tree" class="ztree"></div>
		</div>
	</div>
</div>

<div class="ui-layout-center">
	<div class="container-div">
		<div class="row">
			<div class="col-sm-12 search-collapse">
				<form id="formId">
					<div class="select-list">
						<ul>
							<li>
								<label>地区：</label>
								<select id="city" name="city">
									<option value="">所有</option>
									<option th:each="dict : ${cityList}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
								</select>
							</li>
							<li>
								<label>周期类型：</label>
								<select name="periodType" th:with="type=${@dict.getType('b_period_type')}">
									<option value="">所有</option>
									<option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
								</select>
							</li>
							<li>
								<label>考核周期：</label>
								<input type="text" name="gradePeriod" id="gradePeriod" />
							</li>
							<!--<li>
								<label>年份：</label>
								<select id="createYear" name="createYear">
									<option value="">所有</option>
									<option  th:text="2021" th:value="2021"></option>
									<option  th:text="2020" th:value="2020"></option>
									<option  th:text="2019" th:value="2019"></option>
									<option  th:text="2018" th:value="2018"></option>
									<option  th:text="2017" th:value="2017"></option>
									<option  th:text="2016" th:value="2016"></option>
								</select>
							</li>-->
							<li>
								<a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
								<a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
							</li>
						</ul>
					</div>
				</form>
			</div>

			<div class="col-sm-12 select-table table-striped">
				<table id="bootstrap-table"></table>
			</div>
		</div>
	</div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: layout-latest-js" />
<th:block th:include="include :: ztree-js" />
<th:block th:include="include :: summernote-js" />
<script th:inline="javascript">
		var editFlag = [[${@permission.hasPermi('system:grade:edit')}]];
		var removeFlag = [[${@permission.hasPermi('system:grade:remove')}]];
		var resetPwdFlag = [[${@permission.hasPermi('system:grade:resetPwd')}]];
		var diagnoseFlag=[[${@permission.hasPermi('system:diagnose:list')}]];

		var cityDatas = [[${@dict.getType('b_city')}]];
        var periodTypeDatas = [[${@dict.getType('b_period_type')}]];


		var prefix = ctx + "system/grade";
		var queryGradeId;

		/*跳转到诊断书-*/
		function openDiagnose(id) {
			var url = ctx + 'system/grade/editDiagnose/'+id;
			$.modal.openTab("诊断书管理", url);
		}

		$(function() {
		    var panehHidden = false;
		    if ($(this).width() < 769) {
		        panehHidden = true;
		    }
		    $('body').layout({ initClosed: panehHidden, west__size: 185 });
	     	// 回到顶部绑定
	    	if ($.fn.toTop !== undefined) {
	    		var opt = {
	    			win:$('.ui-layout-center'),
	    			doc:$('.ui-layout-center')
	    		};
	    		$('#scroll-up').toTop(opt);
	    	}
		    queryGradeItems();
		    queryGradeTree();

		    var options = {
                url: prefix + "/gradeQueryList",
                createUrl: prefix + "/add",
                updateUrl: prefix + "/edit/{id}",
                removeUrl: prefix + "/remove",
                exportUrl: prefix + "/export",
                modalName: "信用评分",
                columns: [{
                    checkbox: true
                },
                {
                    field: 'id',
                    title: '评分ID',
                    visible: false
                },
                {
                    field: 'gradeName',
                    title: '信用评分名称',
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a href="javascript:void(0)" onclick="viewGrade(\'' + row.id + '\')">'+value+'</a> ');
                        return actions.join('');
                    }
                },
                {
                    field: 'city',
                    title: '地区',
                    formatter: function(value, row, index) {
                       return $.table.selectDictLabel(cityDatas, value);
                    }
                },
                {
                    field: 'periodType',
                    title: '周期类型',
                    formatter: function(value, row, index) {
                       return $.table.selectDictLabel(periodTypeDatas, value);
                    }
                },
                {
                    field: 'gradePeriod',
                    title: '考核周期'
                },
                {
                    field: 'maxScore',
                    title: '总分'
                },
				{
					field: 'totalScore',
					title: '预评分'
				},
                {
					title: '操作',
					align: 'center',
					formatter: function(value, row, index) {
						var actions = [];
						actions.push('<a class="btn btn-info btn-xs ' + diagnoseFlag + '" href="javascript:void(0)" onclick="openDiagnose(\'' + row.id + '\')"><i class="fa fa-list-ul"></i>诊断书</a> ');
						return actions.join('');
					}
				}
				]
            };
            $.table.init(options);
		});

		function queryGradeItems() {
		}

		function queryGradeTree()
		{
			var url = ctx + "system/grade/treeData";
			var options = {
		        url: url,
		        expandLevel: 2,
		        onClick : zOnClick
		    };
			$.tree.init(options);

			function zOnClick(event, treeId, treeNode) {
				//city和年份赋值，然后调用查询
				if(typeof treeNode.pId !== 'undefined' && treeNode.pId !== null){
					$("#city").val(treeNode.pId);
					//$("#createYear").val(treeNode.id);
					$("#gradePeriod").val(treeNode.id);
				}else{
					$("#city").val(treeNode.id);
					$("#gradePeriod").val("");
				}
				$.table.search();
			}
		}

		$('#btnExpand').click(function() {
			$._tree.expandAll(true);
		    $(this).hide();
		    $('#btnCollapse').show();
		});

		$('#btnCollapse').click(function() {
			$._tree.expandAll(false);
		    $(this).hide();
		    $('#btnExpand').show();
		});

		$('#btnRefresh').click(function() {
			queryGradeTree();
		});

		/*显示已添加评分-*/
		function viewGrade(id) {
		    var url = ctx + 'system/grade/viewGrade/'+id;
		    $.modal.openTab("评分详情", url);
		}

		// 动态获取列
        function ajaxTable(gradeId) {
        	var url = ctx + "system/grade/getTemplateById";
        	//$('#bootstrap-table').empty();
        	$('#bootstrap-table').bootstrapTable('destroy');

            $.modal.loading("正在查询中，请稍后...");
            $.post(url, {"id": gradeId}, function(result) {
                if (result.code == web_status.SUCCESS) {
                	setColumns(result.data,gradeId);
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else {
                    $.modal.alertError(result.msg);
                }
                $.modal.closeLoading();
            });
        }
      	// 设置列
        function setColumns(list,gradeId) {
        	var columns = [];
        	list.forEach(function(item) {
        	    if($.common.equals('status',item.field)){
        	    	columns.push({
        	    		field : item.field,
    					title : item.title,
                        align: 'center',
                        formatter: function(value, row, index) {
                        	return $.table.selectDictLabel(datas, value);
                        }
        	    	})
        	    }else if($.common.equals('weight',item.field)){
        	    	columns.push(
						{
							field: 'weight',
							title: '权重(%)',
							formatter: function (value, row, index) {
								if(typeof value === 'undefined' || value === null || value === ""){
									return ''
								}else{
									return value+'%';
								}
							}
						},
					);
        	    } else {
        	    	columns.push({
        	    		field : item.field,
    					title : item.title
        	    	})
        	    }
        	});


        	initTable(columns,gradeId);

        }
      	// 刷新表格
        function refreshTable(columns) {
        	var options = {
        		columns: columns
        	};
        	$("#" + table.options.id).bootstrapTable('refreshOptions',options);
        }
      	// 初始化表格
        function initTable(columns,gradeId){
        	var options = {
        		url: ctx + "system/grade/getGradeItemsByGradeId?id="+gradeId,
            	showSearch: false,
            	showRefresh: false,
            	showToggle: false,
            	showColumns: false,
            	pagination:false,

            	columns: columns,
            	onLoadSuccess : function(data) {
                    var data = $('#bootstrap-table').bootstrapTable(
                            'getData', true);
                    //合并单元格
                    mergeCells($('#bootstrap-table'), data, "firstColumn", 1);
                    mergeCells($('#bootstrap-table'), data, "secondColumn", 1);
                }
            };
            $.table.init(options);
        }



        /**
		 * 合并单元格
		 * @param data 原始数据(在服务端完成排序)
		 * @param fieldName 合并属性名称
		 * @param colspan 合并列
		 * @param target 目标表格对象
		 */
		function mergeCells(target, data, fieldName, colspan) {
			//声明一个map计算相同属性值在data对象出现的次数和
			var sortMap = {};
			for (var i = 0; i < data.length; i++) {
				for ( var prop in data[i]) {
					if (prop == fieldName) {
						var key = data[i][prop]
						if (sortMap.hasOwnProperty(key)) {
							sortMap[key] = sortMap[key] * 1 + 1;
						} else {
							sortMap[key] = 1;
						}
						break;
					}
				}
			}
			for ( var prop in sortMap) {
				console.log(prop, sortMap[prop])
			}
			var index = 0;
			for ( var prop in sortMap) {
				var count = sortMap[prop] * 1;
				$(target).bootstrapTable('mergeCells', {
					index : index,
					field : fieldName,
					colspan : colspan,
					rowspan : count
				});
				index += count;
			}
		}

	</script>
</body>
</html>